#!/usr/bin/env node

const http = require('http'),
      qs = require('querystring'),
      fs = require('fs');
//url:http://localhost:8080/add?x=2&y=3

http.createServer((req,res)=>{
  //console.log(`${req.method} ${req.url} HTTP/${req.httpVersion}`);
  //console.log(req.headers);
  let out='';
  if(req.url==='/'){
    if(req.method==='GET'){
      //const html=fs.readFileSync('./04-form.html').toString('utf8');
      //html=html.replace('%','');
      res.end(html);
    }else if(req.method==='POST'){
      let data='';
      req.on('data',(chunk)=>{data+=chunk;} );
      req.on('end',()=>{
        out=data;
        console.log(out);
        html=html.replace('%',data);
        res.end(html);
        //console.log(qs.parse(data));
        //res.end('ok');
      });
    }else{
      err(req,res);
    }
  }else{
    err(req,res);
  }
  function err(req,res){
    res.statusCode=404;
    res.end(`${req.url} Not Found`);
  }

}).listen(3000);

let html=`
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title></title>
</head>
<body>
<form method="post" action="http://192.168.228.144:3000/">
  <label>user name:</label>
  <input type="text" name="userName">
  <br>
  <label>password:</label>
  <input type="password" name="password">
  <br>
  <label>&nbsp;</label>
  <input type="submit" value="login">
  <br>
  <div>%</div>
</form>
</body>
</html>`;
